const fs = require('fs')
const path = require('path')

const viewsDir = path.resolve(__dirname, '../src/views')
const outputFilePath = path.resolve(__dirname, './generatedRoutes.ts')

function generateRoutes (dir, basePath = '') {
  const files = fs.readdirSync(dir)
  let routes = []

  files.forEach(file => {
    const fullPath = path.join(dir, file)
    const stat = fs.statSync(fullPath)

    if (stat.isDirectory()) {
      routes = routes.concat(generateRoutes(fullPath, `${basePath}/${file}`))
    } else if (file.endsWith('.vue')) {
      const routePath = `${basePath}/${file.replace('.vue', '')}`
      const componentName = file.replace('.vue', '')
      console.log(`Generating route for: ${fullPath}`)
      routes.push({
        path: componentName.toLowerCase() === 'home' ? '/' : routePath,
        name: componentName.toLowerCase(),
        component: `() => import('./views${routePath}.vue')`
      })
    }
  })

  return routes
}

const routes = generateRoutes(viewsDir)
const routesContent = `
  import { RouteRecordRaw } from 'vue-router';

  const routes: Array<RouteRecordRaw> = ${JSON.stringify(routes, null, 2).replace(/"component": "(.*?)"/g, '"component": $1')};

  export default routes;
`

fs.writeFileSync(outputFilePath, routesContent)
console.log('Routes generated successfully!')
